package com.pagoda.nerp.trade.common;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class CryptUtil {

    private static final String ENCODE = "UTF-8";

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }


    /**
     * 质检平台调用参数
     *
     * @param signFields 参数列表
     * @param param 参数与值的jsonbject
     */
    private static String orgSignSrc(String[] signFields, JSONObject param) {
        if (signFields != null) {
            Arrays.sort(signFields); // 对key按照 字典顺序排序
        }

        StringBuffer signSrc = new StringBuffer("");
        int i = 0;
        for (String field : signFields) {
            signSrc.append(field);
            signSrc.append("=");
            signSrc.append((StringUtils.isEmpty(param.getString(field)) ? ""
                    : param.getString(field)));
            // 最后一个元素后面不加&
            if (i < (signFields.length - 1)) {
                signSrc.append("&");
            }
            i++;
        }
        return signSrc.toString();
    }

    /**
     * MD5生成签名字符串
     *
     * @param map 需签名参数
     * @return
     */
    public static String MD5sign(Map<String, Object> map, String key) {
        String genSign = "";
        try {

            String[] strArray = new String[map.keySet().size()];      //定义长度为6的字符串数组
            String[] signFields = map.keySet().toArray(strArray);  //将集合转换为字符串数组形式

            JSONObject param_json = new JSONObject(true);
            TreeMap treeMap = (TreeMap) map.get("param_json");
            Iterator titer=treeMap.entrySet().iterator();
            while(titer.hasNext()){
                Map.Entry ent=(Map.Entry )titer.next();
                param_json.put(ent.getKey().toString(), ent.getValue().toString());
            }
            map.put("param_json", param_json);

            JSONObject mapJson = (JSONObject) JSONObject.toJSON(map);
            // 生成签名原文
            String signSrc = orgSignSrc(signFields, mapJson);
            // MD5的方式签名
            signSrc =key+signSrc+key;
            genSign = getMessageDigest(signSrc);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return genSign.toUpperCase();
    }


    /**
     * 功能：MD5加密
     * @param strSrc 加密的源字符串
     * @return 加密串 长度32位(hex串)
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String getMessageDigest(String strSrc) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = null;
        String strDes = null;
        final String ALGO_MD5 = "MD5";

        byte[] bt = strSrc.getBytes(ENCODE);
        md = MessageDigest.getInstance(ALGO_MD5);
        md.update(bt);
        strDes = bytes2Hex(md.digest());
        return strDes;
    }

    /**
     * 将字节数组转为HEX字符串(16进制串)
     * @param bts 要转换的字节数组
     * @return 转换后的HEX串
     */
    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    static class MapKeyComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }

}
